<template>
	<view class="content" @click="sure">
		<view class="setting" @click.stop="">
			<radio-group @change="radioChange" v-show="false" class="book-group">
				<label class="book" style="width: 33%;" v-for="(item, index) in bookItem" :key="item.value">
					<view>
						<radio :value="item.value" :checked="index === current" />
					</view>
					<view>{{item.name}}</view>
				</label>
			</radio-group>
			<view class="setting-max-stroke">
				<view class="text-key">设置最大笔画数：</view>
				<input class="name-input" placeholder="请输入" type="number" v-model="maxNumber" />
			</view>
			<view class="setting-max-stroke">
				<view class="text-key">切换数据源：</view>
				<view class="btn-change" style="margin-left: 10px;" @click.stop="queryJson">
					切换</view>
			</view>
			<view class="setting-max-stroke">
				<view class="text-key">取词方式：</view>
				<radio-group @change="pickChange" class="book-group">
					<label class="book" v-for="(item, index) in pickStyle" :key="item.value">
						<view>
							<radio :value="item.value" :checked="item.value === currentPickStyle" />
						</view>
						<view>{{item.name}}</view>
					</label>
				</radio-group>
			</view>
		</view>
		<view class="line" />
		<view class="handle" @click.stop="">
			<view class="text-area">
				<view class="result-content" style="color: red;">{{result.name}}</view>
				<view class="btn-score" style="margin-left: 10px;" v-if="result.name" @click="score">
					查看评分</view>
			</view>
			<view class="result">
				<view class="result-delete">
					<view class="text-key">拉黑：</view>
					<view class="btn-delete" v-show="result0" @click.stop="deleteChar(0)">拉黑 "{{result0}}"</view>
					<view class="btn-delete" v-if="result1" style="margin-left: 10px;" @click.stop="deleteChar(1)">
						拉黑"{{result1}}"</view>
				</view>
				<view class="name-xinhua">
					<view class="text-key">查字典：</view>
					<view class="btn-xinhua" v-show="result0" @click.stop="look(0)">查看 "{{result0}}"</view>
					<view class="btn-xinhua" style="margin-left: 10px;" v-if="result1" @click.stop="look(1)">
						查看"{{result1}}"</view>
				</view>
			</view>
		</view>
		<view class="line" />
		<view class="result">
			<text class="text-key">作者：{{result.author}}</text>
			<text class="text-key">标题：{{result.title}}</text>
			<rich-text class="text-key" :nodes="lightName"></rich-text>
		</view>
	</view>
	</view>
</template>

<script>
	import cnchar from 'cnchar';
	var that;
	export default {
		data() {
			return {
				title: 'Hello',
				bookItem: [{
					value: 'quan-tang-shi',
					name: '全唐诗',
					checked: true,
					jsonContent: ""
				}],
				pickStyle: [{
					value: 'firstEnd',
					name: '首尾字',
					checked: true,
				}, {
					value: 'nearby',
					name: '相邻字',
					checked: false,
				}, {
					value: 'random',
					name: '随机',
					checked: false,
				}],
				current: 0,
				currentPickStyle: "firstEnd",
				maxNumber: 20,
				result: {},
				badChars: "胸鬼懒禽鸟鸡我邪罪凶丑仇鼠蟋蟀淫秽妹狐鸡鸭蝇悔鱼肉苦犬吠窥血丧饥女搔父母昏狗蟊疾病痛死潦哀痒害蛇牲妇狸鹅穴畜烂兽靡爪氓劫鬣螽毛婚姻匪婆羞辱"
			}
		},
		onLoad() {
			that = this;
			this.queryJson();
			uniCloud.callFunction({
				name: "query_bad_char",
				success(res) {
					this.badChars = res.result[0].bad_char
				}
			})
		},
		computed: {
			lightName: function() {
				if (this.result.name && this.result.name.length > 0) {
					console.log(JSON.stringify(this.result));
					console.log(JSON.stringify(this.result.content));
					console.log(this.result.content[0]);
					var splitName = this.result.name.split("");
					if (splitName.length == 2) {
						var str = this.result.content[0]
						return str.replace(
							splitName[0],
							"<span style='color: #5584E8;'>" + splitName[0] + "</span>"
						).replace(
							splitName[1],
							"<span style='color: #5584E8;'>" + splitName[1] + "</span>"
						);
					} else if (splitName.length == 1) {
						var str = this.result.content[0]
						return str.replace(splitName[0],
							"<span style='color: #5584E8;'>" + splitName[0] + "</span>"
						);
					}
					return "内容：" + this.result.content[0]
				} else {
					return "内容："
				}
			},
			result0: function() {
				if (this.result.name && this.result.name.length > 0) {
					var splitName = this.result.name.split("");
					return splitName[0]
				} else {
					return ""
				}
			},
			result1: function() {
				if (this.result.name && this.result.name.length == 2) {
					console.log(JSON.stringify(this.result));
					console.log(this.result.name);
					var splitName = this.result.name.split("");
					return splitName[1]
				} else {
					return ""
				}
			}
		},
		methods: {
			queryJson() {
				uniCloud.callFunction({
					name: "get-json-list",
					success(res) {
						var jsonList = res.result.data
						var index = Math.floor(Math.random() * jsonList.length)
						console.log(jsonList.length);
						that.bookItem[0].content = jsonList[index];
						uni.request({
							url: jsonList[index].jsonPath, //仅为示例，并非真实接口地址。
							complete: (jsonStr) => {
								that.bookItem[0].jsonContent = jsonStr;
							}
						});
					}
				})
			},
			score() {
				uni.navigateTo({
					url: '/pages/name_score/name_score?name=' + this.result.name
				});
			},
			look(num) {
				var word = "";
				if (num == 0) {
					word = this.result0;
				} else if (num == 1) {
					word = this.result1;
				}
				uni.navigateTo({
					url: '/pages/word_detail/word_detail?word=' + word
				});
			},
			deleteChar(num) {
				if (num == 0) {
					this.badChars += this.result0;
				} else if (num == 1) {
					this.badChars += this.result1;
				}
				uniCloud.callFunction({
					name: "change_bad_chars",
					data: {
						bad_char: this.badChars,
					},
					success(call) {
						console.log(call);
					},
				})
				this.sure();
			},
			sure() {
				var jsonContent = this.bookItem[this.current].jsonContent
				var randJson = this.genName(jsonContent.data)
				var trueName = this.cleanBadChar(this.cleanPunctuation(randJson.name))
				let stroke = cnchar.stroke(randJson.name);
				let stroke1 = cnchar.stroke(randJson.name.split("")[0]);
				let stroke2 = cnchar.stroke(randJson.name.split("")[1]);
				if (trueName.length < 2 ||
					stroke == 0 ||
					stroke > this.maxNumber ||
					stroke == stroke1 ||
					stroke == stroke2) {
					this.sure();
				} else {
					this.result = randJson;
				}
			},
			cleanBadChar(str) {
				if (!str) {
					return ""
				}
				const badChars = this.badChars.split('');
				return str.split('').filter(char => badChars.indexOf(char) === -1).join('');
			},
			radioChange(index) {
				this.current = index;
			},
			pickChange(info) {
				this.currentPickStyle = info.detail.value;
				this.pickStyle.forEach(item => {
					if (item.value == this.currentPickStyle) {
						item.checked = true
					}
				})
			},

			genName(dataArr) {
				const randPoem = this.genRandPoem(dataArr);
				const sentences = this.splitSentence(randPoem.paragraphs[0]);
				const randSentence = sentences[this.randBetween(0, sentences.length)];
				const name = {};
				if (this.currentPickStyle == "firstEnd") { //首尾字
					const puncReg = /[<>《》！*\(\^\)\$%~!@#…&%￥—\+=、。，？；‘’“”：·`]/g;
					var splitP = randSentence.split(puncReg)
					var list = []
					for (var i = 0; i < splitP.length; i++) {
						if (splitP[i].length > 0) {
							list.push(splitP[i][0])
							list.push(splitP[i][splitP[i].length - 1])
						}
					}
					name.name = this.randCharFromStr(list.join(""), 2);
				} else if (this.currentPickStyle == "nearby") { //相邻字
					const cleanSentence = this.cleanPunctuation(randSentence);
					var index = Math.floor(Math.random() * cleanSentence.length)
					if (index < cleanSentence.length) {
						name.name = cleanSentence[index] + cleanSentence[index + 1]
					}
				} else { //随机
					const cleanSentence = this.cleanPunctuation(randSentence);
					name.name = this.randCharFromStr(cleanSentence, 2);
				}
				name.title = randPoem.title;
				name.book = randPoem.book;
				name.sentence = randSentence;
				name.content = randPoem.paragraphs;
				name.author = randPoem.author ? randPoem.author : '佚名';
				name.dynasty = randPoem.dynasty;
				return name;
			},
			// 清除标点符号
			cleanPunctuation(str) {
				if (!str) {
					return ""
				}
				const puncReg = /[<>《》！*\(\^\)\$%~!@#…&%￥—\+=、。，？；‘’“”：·`]/g;
				if (!str) {
					return str
				}
				return str.replace(puncReg, '');
			},
			splitSentence(str) {
				if (!str) {
					return []
				}
				str = this.cleanStr(str);
				if (!str) {
					return []
				}
				str = str.replace(/！|。|？|；/g, str => `${str}|`);
				str = str.replace(/\|$/g, '');
				let arr = str.split('|');
				arr = arr.filter(item => item.length >= 2);
				return arr;
			},
			cleanStr(str) {
				if (!str) {
					return ""
				}
				str = str.replace(/\s|<br>|<p>|<\/p>|　|”|“/g, '');
				str = str.replace(/\(.+\)/g, '');
				return str;
			},
			randBetween(min, max) {
				// [min,max)  max is not included
				return min + Math.floor(Math.random() * (max - min));
			},
			genRandPoem(dataArr) {
				let index = this.randBetween(0, dataArr.length);
				while (!dataArr[index].paragraphs) {
					index = this.randBetween(0, dataArr.length);
				}
				return dataArr[index];
			},
			randCharFromStr(str, num, ordered) {
				if (typeof ordered === 'undefined') {
					ordered = true;
				}
				let randNumArr = this.genRandNumArr(str.length, num);
				if (ordered) {
					randNumArr = randNumArr.sort((a, b) => a - b);
				}
				let res = '';
				for (let i = 0; i < randNumArr.length; i++) {
					res += str.charAt(randNumArr[i]);
				}
				return res;
			},
			genRandNumArr(max, num) {
				if (num > max) {
					num = max;
					console.log(`max=${max} num = ${num}`);
					// throw new Error('too large num');
				}
				const orderedNum = [];
				for (var i = 0; i < max; i++) {
					orderedNum.push(i);
				}
				const res = [];
				for (var i = 0; i < num; i++) {
					const randIndex = this.randBetween(0, orderedNum.length);
					const randNum = orderedNum[randIndex];
					res.push(randNum);
					orderedNum.splice(randIndex, 1);
					// console.log('i=' + i + 'rand=' + rand, orderedNum);
				}
				return res;
			}


		}
	}
</script>

<style lang="scss">
	.content {
		position: absolute;
		left: 0;
		bottom: 0;
		top: 0;
		right: 0;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.text-key {
			margin-left: 20rpx;
		}

		.book-group {
			padding: 10px;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
		}

		.book {
			display: flex;
			flex-grow: 0;
		}

		.setting-max-stroke {
			display: flex;
			align-items: center;
		}

		.btn-change {
			width: 120rpx;
			height: 40rpx;
			background-color: green;
			border-radius: 20px;
			padding: 5px 10px;
			font-size: 14px;
			color: white;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.text-area {
			width: 750rpx;
			display: flex;
			align-items: center;

			.result-content {
				display: flex;
				justify-content: flex-end;
				width: 375rpx;
				border-radius: 20px;
				padding: 5px 10px;
				font-size: 34px;
			}

			.btn-score {
				height: 40rpx;
				width: 150rpx;
				background-color: green;
				border-radius: 20px;
				padding: 5px 10px;
				font-size: 14px;
				color: white;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.line {
			height: 5px;
			margin-top: 10px;
			width: 750rpx;
			background-color: #EFEFEF;
		}

		.result {
			width: 750rpx;
			display: flex;
			margin-top: 10px;
			flex-direction: column;
			align-items: flex-start;


			.result-delete {
				display: flex;
				justify-content: center;
				align-items: center;

				.btn-delete {
					height: 40rpx;
					width: 150rpx;
					background-color: red;
					border-radius: 20px;
					padding: 5px 10px;
					font-size: 14px;
					color: white;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}


			.name-xinhua {
				width: 710rpx;
				margin-top: 10px;
				display: flex;
				align-items: center;

				.btn-xinhua {
					width: 150rpx;
					height: 40rpx;
					background-color: green;
					border-radius: 20px;
					padding: 5px 10px;
					font-size: 14px;
					color: white;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.result {
				width: 710rpx;
			}

		}
	}
</style>
